﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataTier;
using System.Data.SqlClient;
using System.Data.Common;


namespace DbLayer
{
    public class DbLocation : DbObject, IDbLocation
    {

        private static DbLocation _instance = null;
        private IDictionary<int, Location> _locationDict = null;

        private DbLocation()
        {
        }

        public static IDbLocation Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DbLocation();
                }
                return _instance;
            }
        }

        public void AddLocation(Location location)
        {
            string statement = BuildInsertStatement("Location", GetNextId("Location", "id").ToString(), location.Identifier);
            ExecuteStatement(statement);
        }

        public Location GetLocation(int id)
        {

            if (_locationDict == null)
            {
                LoadLocations();
            }

            return _locationDict[id];

        }

        public IList<Location> GetAllLocations()
        {

            if (_locationDict == null)
            {
                LoadLocations();
            }

            return _locationDict.Values.ToList();

        }

        private void LoadLocations()
        {

            _locationDict = new Dictionary<int, Location>();

            IList<Location> locations = BuildAllLocations();

            foreach (Location loc in locations)
            {
                _locationDict.Add(loc.Id, loc);
            }

            IList<Connection> connections = DbConnection.Instance.GetAllConnections();

            foreach (Connection con in connections)
            {
                con.From.AddConnection(con);
            }

        }

        private IList<Location> BuildAllLocations()
        {

            List<Location> locations = new List<Location>();
            string statement = BuildSelectStatement("Location", "");
            SqlDataReader reader = ExecuteQuery(statement);

            while (reader.Read())
            {
                locations.Add(BuildLocation(reader));
            }

            reader.Close();

            return locations;

        }

        private Location BuildLocation(SqlDataReader reader)
        {

            Location location = new Location();

            location.Identifier = reader["Identifier"].ToString();
            location.Id = Convert.ToInt32(reader["Id"]);

            return location;

        }

    }
}
